package com.nearby.demand.fragment;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.nearby.demand.R;
import com.nearby.demand.adapter.MyAdapter;
import com.nearby.demand.adapter.SimpleFragmentPagerAdapter;
import com.nearby.demand.adapter.listener.OnItemClickListener;
import com.nearby.demand.application.Constant;
import com.nearby.demand.db.DaoMaster;
import com.nearby.demand.db.DaoSession;
import com.nearby.demand.db.Demand;
import com.nearby.demand.db.DemandDao;
import com.nearby.demand.ui.auto.DemoActivity;
import com.nearby.demand.utils.KLog;
import com.nearby.demand.widget.HidingScrollListener;
import com.request.ok.http.OkHttpUtils;
import com.request.ok.http.callback.StringCallback;
import com.squareup.okhttp.Request;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * Created by Administrator on 2015/11/18.
 */
public class PageFragment extends BaseFragment {
    public static final String ARG_PAGE = "ARG_PAGE";
    private int mPage;
    private View layout;
    MyAdapter mAdapter;

    public static PageFragment newInstance(Bundle args) {
        PageFragment pageFragment = new PageFragment();
        pageFragment.setArguments(args);
        return pageFragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPage = getArguments().getInt(ARG_PAGE);

    }


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    private ItemTouchHelper mItemTouchHelper;
    RecyclerView recycler_view;
    PtrClassicFrameLayout mPtrFrame;

    DaoMaster.DevOpenHelper helper;
    DaoMaster master;
    DaoSession session;
    DemandDao dao;
    SQLiteDatabase db;
    Cursor cursor;
    List<Demand> demands = new ArrayList<Demand>();

    public class MyStringCallback extends StringCallback {
        @Override
        public void onBefore(Request request) {
            super.onBefore(request);
            KLog.i("TAG", "onBefore");
        }

        @Override
        public void onAfter() {
            super.onAfter();
            KLog.i("TAG", "onAfter");
        }

        @Override
        public void onError(Request request, Exception e) {
            KLog.i("TAG", "onError-" + e.toString());
        }

        @Override
        public void onResponse(String response) {
            KLog.i("TAG", "onResponse-" + response);
            //has protected access in
            try {
                JSONArray jsonArray = new JSONArray(response);
                int size = jsonArray.length();
                for (int i = 0; i < size; i++) {
                    JSONObject json = jsonArray.optJSONObject(i);
                    Demand demand = new Demand();
                    demand.setStBg(Constant.BASE_URL + json.optString("releaseInfoUrl"));
                    demand.setStLabel(json.optString("releaseAddress"));
                    demands.add(demand);
                }
                mAdapter.addList(demands);
                //                Gson gson = new Gson();
                //                java.lang.reflect.Type type =
                //                        new com.google.gson.reflect.TypeToken<List<Demand>>() {
                //                        }.getType();
                //                demands = gson.fromJson(response, type);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        @Override
        public void inProgress(float progress) {
            KLog.i("TAG", "inProgress");
        }
    }


    public void initDemands() {
        OkHttpUtils
                .get()
                .url(Constant.BASE_URL + "/requestIndex")
                .build()
                .execute(new MyStringCallback());
        //        demands = StringUtils.loadDemoColorItems(getActivity());

        //        helper = new DaoMaster.DevOpenHelper(getActivity(), "demand-db", null);
        //        db = helper.getWritableDatabase();
        //        master = new DaoMaster(db);
        //        session = master.newSession();
        //        dao = session.getDemandDao();
        //        demands = dao.queryBuilder().list();
        //        for (Demand demand : demands) {
        ////            KLog.i("i=" + demand.getStPid());
        //        }
    }

    RelativeLayout relativeLayout;
    LinearLayout fabtoolbar_toolbar;
    TabLayout sliding_tabs;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (layout == null) {
            layout = inflater.inflate(R.layout.page_fragment, container, false);
            initDemands();
            relativeLayout = (RelativeLayout) getActivity().findViewById(R.id.fabtoolbar_container);



            fabtoolbar_toolbar = (LinearLayout) getActivity().findViewById(R.id.fabtoolbar_toolbar);

            sliding_tabs = (TabLayout) getActivity().findViewById(R.id.sliding_tabs);

            recycler_view = (RecyclerView) layout.findViewById(R.id.recycler_view);
            mPtrFrame = (PtrClassicFrameLayout) layout.findViewById(R.id.rotate_header_list_view_frame);
            mPtrFrame.setLastUpdateTimeRelateObject(this);
            mPtrFrame.setPtrHandler(new PtrDefaultHandler2() {

                @Override
                public void onRefreshBegin(PtrFrameLayout frame) {
                    // TODO Auto-generated method stub
                    mPtrFrame.refreshComplete();
                }

                @Override
                public void onLoadMoreBegin(PtrFrameLayout frame) {
                    // TODO Auto-generated method stub
                    mPtrFrame.refreshComplete();
                }

            });
            // the following are default settings
            mPtrFrame.setResistance(1.7f);
            mPtrFrame.setRatioOfHeaderHeightToRefresh(1.2f);
            mPtrFrame.setDurationToClose(200);
            mPtrFrame.setDurationToCloseHeader(1000);
            // default is false
            mPtrFrame.setPullToRefresh(false);
            // default is true
            mPtrFrame.setKeepHeaderWhenRefresh(true);


            mAdapter = new MyAdapter(demands);
            //            mAdapter.setOnItemClickListener(new OnItemClickListener() {
            //                @Override
            //                public void onClick(int position, View view, Object item) {
            //                    Demand items = (Demand) item;
            //                    Toast.makeText(getActivity(), "短" + items.getStPid(), Toast.LENGTH_SHORT).show();
            //
            //                }
            //            });
            mAdapter.setOnItemClickListener(new OnItemClickListener<Demand>() {

                @Override
                public void onClick(View view, Demand item) {
                    Toast.makeText(getActivity(), "短" + item.getStPid(), Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(getActivity(), DemoActivity.class));

                }
            });
            //
            //            mAdapter.setOnItemLongClickListener(new OnItemLongClickListener<Demand>() {
            //                @Override
            //                public void onLongClick(View view, Demand item) {
            //                    Toast.makeText(getActivity(), "长按", Toast.LENGTH_SHORT).show();
            //                }
            //            });
            recycler_view.setHasFixedSize(true);//固定尺寸
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
            recycler_view.setLayoutManager(linearLayoutManager);
            //            recycler_view.addItemDecoration(new DividerItemDecoration(getActivity(),
            //                    DividerItemDecoration.VERTICAL_LIST));
            recycler_view.setAdapter(mAdapter);

            recycler_view.addOnScrollListener(new HidingScrollListener() {
                @Override
                public void onHide() {
                    hideViews();
                }

                @Override
                public void onShow() {
                    showViews();
                }
            });

            Bundle bundle = getArguments();
            if (bundle != null) {
                mCurIndex = bundle.getInt(ARG_PAGE);
            }
            isPrepared = true;
            lazyLoad();
        }

        return layout;
    }

    private void hideViews() {
        sliding_tabs.animate().translationY(-sliding_tabs.getHeight()).setInterpolator(new AccelerateInterpolator(2));



        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) relativeLayout.getLayoutParams();
        int fabBottomMargin = lp.bottomMargin;
        relativeLayout.animate().translationY(relativeLayout.getHeight() + fabBottomMargin).setInterpolator(new AccelerateInterpolator(2)).start();


        RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) fabtoolbar_toolbar.getLayoutParams();
        int fabBottomMargins = lps.bottomMargin;
        fabtoolbar_toolbar.animate().translationY(fabtoolbar_toolbar.getHeight() + fabBottomMargins).setInterpolator(new AccelerateInterpolator(2)).start();




    }

    private void showViews() {
        sliding_tabs.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2));
        relativeLayout.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();
        fabtoolbar_toolbar.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();

    }

    private Point getLocationInView(View src, View target) {
        final int[] l0 = new int[2];
        src.getLocationOnScreen(l0);

        final int[] l1 = new int[2];
        target.getLocationOnScreen(l1);

        l1[0] = l1[0] - l0[0] + target.getWidth() / 2;
        l1[1] = l1[1] - l0[1] + target.getHeight() / 2;

        return new Point(l1[0], l1[1]);
    }

    private int getColor(View view) {
        return Color.parseColor((String) view.getTag());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    boolean clickRequest = false;
    SimpleFragmentPagerAdapter sPagerAdapter;

    public void onClickRequest(boolean init, SimpleFragmentPagerAdapter simpleFragmentPagerAdapter) {
        this.clickRequest = init;
        sPagerAdapter = simpleFragmentPagerAdapter;
        initRequest();

    }

    public void initRequest() {
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        //        setUserVisibleHint(true);
        super.onActivityCreated(savedInstanceState);
    }


    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || mHasLoadedOnce) {
            return;
        }
        initRequest();

    }

    private final int FIRST_FRAGMENT = 0;
    private final int SECOND_FRAGMENT = 1;
    private final int THIRD_FRAGMENT = 2;


    private int mCurIndex = -1;
    /**
     * 标志位，标志已经初始化完成
     */
    private boolean isPrepared;
    /**
     * 是否已被加载过一次，第二次就不再去请求数据了
     */
    private boolean mHasLoadedOnce;

}
